package com.mfs.proxy.core.server.registry;

import com.alibaba.fastjson2.JSON;
import com.mfs.proxy.core.exceptions.ProxyException;
import com.mfs.proxy.core.client.ProxyClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 超时代理客户端注册中心
 * 注册到该注册中心的代理客户端都有一个超时时间，如果在超时之前没有续期，
 * 则会从将该代理客户端关闭并从注册中心移除
 *
 * @author mfs
 * @date 2023/7/1 14:54
 **/
public abstract class AbstractTimeoutProxyClientRegistry extends AbstractProxyClientRegistry {
    private static Logger logger = LoggerFactory.getLogger(AbstractTimeoutProxyClientRegistry.class);

    @Override
    public boolean register(String proxyIp, Integer proxyPort, ProxyClient proxyClient) {
        boolean success = super.register(proxyIp, proxyPort, proxyClient);
        if (success) {
            if (!timeoutRegister(proxyIp, proxyPort)) {
                success = super.unregister(proxyIp, proxyPort);
                if (!success) {
                    logger.error("代理客户端超时注册失败后，注销代理客户端异常, {}", JSON.toJSONString(proxyClient));
                    throw new ProxyException("注销代理客户端异常");
                }
                return false;
            }
            return true;
        }
        return false;
    }

    @Override
    public boolean unregister(String proxyIp, Integer proxyPort) {
        boolean success = super.unregister(proxyIp, proxyPort);
        if (success) {
            return timeoutUnregister(proxyIp, proxyPort);
        }
        return false;
    }

    /**
     * 超时注册
     * */
    public abstract boolean timeoutRegister(String proxyIp, Integer proxyPort);

    /**
     * 超时注销
     * */
    public abstract boolean timeoutUnregister(String proxyIp, Integer proxyPort);

    /**
     * 注册保活
     * */
    public abstract void hello(String proxyIp, Integer proxyPort);
}
